<template>
  <div class="supply-chain-dashboard">
    <!-- 页面标题和控制栏 -->
    <div class="dashboard-header">
      <div class="header-left">
        <h1 class="dashboard-title">
          <el-icon class="title-icon"><Van /></el-icon>
          供应链看板
        </h1>
        <div class="update-time">最后更新时间: {{ updateTime }}</div>
      </div>
      <div class="header-controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :shortcuts="dateShortcuts"
          @change="handleDateChange"
        />
        <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 概览指标卡片 -->
    <div class="overview-metrics">
      <div class="metrics-grid">
        <div class="metric-card total-inventory">
          <div class="metric-icon">
            <el-icon><Box /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatCurrency(overviewData.totalInventoryAmount) }}</div>
            <div class="metric-label">总库存金额（万元）</div>
          </div>
        </div>

        <div class="metric-card spot-amount">
          <div class="metric-icon">
            <el-icon><House /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatCurrency(overviewData.spotAmount) }}</div>
            <div class="metric-label">现货金额（万元）</div>
          </div>
        </div>

        <div class="metric-card transit-amount">
          <div class="metric-icon">
            <el-icon><Van /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatCurrency(overviewData.inTransitAmount) }}</div>
            <div class="metric-label">在途金额（万元）</div>
          </div>
        </div>

        <div class="metric-card turnover-days">
          <div class="metric-icon">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ overviewData.avgTurnoverDays }}</div>
            <div class="metric-label">平均周转天数</div>
          </div>
        </div>

        <div class="metric-card alert-count">
          <div class="metric-icon">
            <el-icon><WarningFilled /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ overviewData.alertProductCount }}</div>
            <div class="metric-label">预警商品数</div>
          </div>
        </div>

        <div class="metric-card active-stores">
          <div class="metric-icon">
            <el-icon><Shop /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ overviewData.activeStoreCount }}</div>
            <div class="metric-label">活跃店铺数</div>
          </div>
        </div>

        <div class="metric-card pv-spot-rate">
          <div class="metric-icon">
            <el-icon><PieChart /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatPercentage(overviewData.pvSpotRate) }}</div>
            <div class="metric-label">PV现货率</div>
          </div>
        </div>

        <div class="metric-card achievement-rate">
          <div class="metric-icon">
            <el-icon><Trophy /></el-icon>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatPercentage(targetData.achievementRate) }}</div>
            <div class="metric-label">目标达成率</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要分析区域 -->
    <div class="main-analysis">
      <el-row :gutter="24">
        <!-- 库存分析 -->
        <el-col :span="12">
          <div class="analysis-card">
            <div class="card-header">
              <h3>库存结构分析</h3>
              <el-tag
                :type="
                  getHealthStatusType(inventoryData.inventoryHealthStatus) as
                    | 'success'
                    | 'primary'
                    | 'warning'
                    | 'danger'
                    | 'info'
                "
              >
                {{ inventoryData.inventoryHealthStatus }}
              </el-tag>
            </div>
            <div class="card-content">
              <div class="inventory-chart-container">
                <div ref="inventoryChartRef" class="chart-container"></div>
              </div>
              <div class="inventory-stats">
                <div class="stat-item">
                  <span class="stat-label">现货占比:</span>
                  <span class="stat-value">{{ formatPercentage(inventoryData.spotRatio) }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-label">在途占比:</span>
                  <span class="stat-value">
                    {{ formatPercentage(inventoryData.inTransitRatio) }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 周转分析 -->
        <el-col :span="12">
          <div class="analysis-card">
            <div class="card-header">
              <h3>周转效率分析</h3>
              <div class="efficiency-change">
                <el-icon v-if="turnoverData.turnoverEfficiencyChange >= 0" class="trend-up">
                  <Top />
                </el-icon>
                <el-icon v-else class="trend-down">
                  <Bottom />
                </el-icon>
                {{ formatPercentage(Math.abs(turnoverData.turnoverEfficiencyChange)) }}
              </div>
            </div>
            <div class="card-content">
              <div class="turnover-distribution">
                <div class="turnover-item fast">
                  <div class="turnover-label">快周转 (&lt;30天)</div>
                  <div class="turnover-count">{{ turnoverData.fastTurnoverCount }}</div>
                </div>
                <div class="turnover-item medium">
                  <div class="turnover-label">中周转 (30-60天)</div>
                  <div class="turnover-count">{{ turnoverData.mediumTurnoverCount }}</div>
                </div>
                <div class="turnover-item slow">
                  <div class="turnover-label">慢周转 (&gt;60天)</div>
                  <div class="turnover-count">{{ turnoverData.slowTurnoverCount }}</div>
                </div>
              </div>
              <div class="best-performance">
                <div class="best-store">
                  <el-icon class="star-icon"><StarFilled /></el-icon>
                  最佳周转: {{ turnoverData.bestTurnoverStore }} ({{
                    turnoverData.bestTurnoverDays
                  }}天)
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 目标达成和店铺排行 -->
    <div class="target-and-ranking">
      <el-row :gutter="24">
        <!-- 目标达成 -->
        <el-col :span="8">
          <div class="analysis-card">
            <div class="card-header">
              <h3>目标达成情况</h3>
              <el-tag
                :type="
                  getTargetStatusType(targetData.targetStatus) as
                    | 'success'
                    | 'primary'
                    | 'warning'
                    | 'danger'
                    | 'info'
                "
              >
                {{ targetData.targetStatus }}
              </el-tag>
            </div>
            <div class="card-content">
              <div class="target-progress">
                <div class="progress-info">
                  <div class="progress-labels">
                    <span>已下单</span>
                    <span>{{ formatPercentage(targetData.achievementRate) }}</span>
                  </div>
                  <el-progress
                    :percentage="targetData.achievementRate"
                    :color="getProgressColor(targetData.achievementRate)"
                    :stroke-width="8"
                  />
                </div>
                <div class="target-details">
                  <div class="detail-item">
                    <span class="label">月度目标:</span>
                    <span class="value">{{ formatCurrency(targetData.monthlyNrTarget) }}万</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">已下单:</span>
                    <span class="value">{{ formatCurrency(targetData.orderedAmount) }}万</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">差额:</span>
                    <span class="value gap">{{ formatCurrency(targetData.targetGap) }}万</span>
                  </div>
                  <div class="detail-item">
                    <span class="label">预计完成:</span>
                    <span class="value">{{ targetData.estimatedCompletionDate }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 店铺表现排行 -->
        <el-col :span="16">
          <div class="analysis-card">
            <div class="card-header">
              <h3>店铺表现排行</h3>
              <el-select v-model="sortBy" @change="handleSortChange" class="sort-selector">
                <el-option label="达成率" value="achievementRate" />
                <el-option label="周转天数" value="turnoverDays" />
                <el-option label="库存金额" value="inventoryAmount" />
                <el-option label="PV现货率" value="pvSpotRate" />
              </el-select>
            </div>
            <div class="card-content">
              <div class="ranking-table">
                <div class="table-header">
                  <div class="rank-col">排名</div>
                  <div class="store-col">店铺</div>
                  <div class="amount-col">库存金额(万)</div>
                  <div class="days-col">周转天数</div>
                  <div class="rate-col">达成率</div>
                  <div class="spot-col">PV现货率</div>
                  <div class="trend-col">趋势</div>
                </div>
                <div class="table-body">
                  <div
                    v-for="(store, index) in storeRanking"
                    :key="`store-${store.id || store.storeName}-${index}`"
                    class="table-row"
                    :class="{ 'top-performer': store.ranking <= 3 }"
                  >
                    <div class="rank-col">
                      <span class="rank-number" :class="`rank-${store.ranking}`">
                        {{ store.ranking }}
                      </span>
                    </div>
                    <div class="store-col">{{ store.storeName }}</div>
                    <div class="amount-col">{{ formatCurrency(store.inventoryAmount) }}</div>
                    <div class="days-col">{{ store.turnoverDays }}</div>
                    <div class="rate-col">{{ formatPercentage(store.achievementRate) }}</div>
                    <div class="spot-col">{{ formatPercentage(store.pvSpotRate) }}</div>
                    <div class="trend-col">
                      <el-icon :class="`trend-${store.trend}`">
                        <Top v-if="store.trend === 'up'" />
                        <Bottom v-else-if="store.trend === 'down'" />
                        <Minus v-else />
                      </el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 预警信息和趋势图表 -->
    <div class="alerts-and-trends">
      <el-row :gutter="24">
        <!-- 库存预警 -->
        <el-col :span="12">
          <div class="analysis-card">
            <div class="card-header">
              <h3>库存预警</h3>
              <el-badge :value="alertList.length" class="alert-badge">
                <el-icon><WarningFilled /></el-icon>
              </el-badge>
            </div>
            <div class="card-content">
              <div class="alert-list">
                <div
                  v-for="(alert, index) in alertList"
                  :key="`alert-${alert.storeName}-${alert.alertType}-${index}`"
                  class="alert-item"
                  :class="`alert-${alert.alertLevel}`"
                >
                  <div class="alert-header">
                    <div class="alert-store">{{ alert.storeName }}</div>
                    <el-tag
                      :type="
                        getAlertLevelType(alert.alertLevel) as
                          | 'success'
                          | 'primary'
                          | 'warning'
                          | 'danger'
                          | 'info'
                      "
                      size="small"
                    >
                      {{ getAlertLevelText(alert.alertLevel) }}
                    </el-tag>
                  </div>
                  <div class="alert-description">{{ alert.alertDescription }}</div>
                  <div class="alert-action">
                    <el-icon><Bell /></el-icon>
                    {{ alert.recommendedAction }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 趋势图表 -->
        <el-col :span="12">
          <div class="analysis-card">
            <div class="card-header">
              <h3>关键指标趋势</h3>
              <el-radio-group v-model="selectedTrend" @change="handleTrendChange" size="small">
                <el-radio-button label="inventory">库存金额</el-radio-button>
                <el-radio-button label="turnover">周转天数</el-radio-button>
                <el-radio-button label="achievement">达成率</el-radio-button>
              </el-radio-group>
            </div>
            <div class="card-content">
              <div ref="trendChartRef" class="chart-container"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  Bell,
  Bottom,
  Box,
  Clock,
  House,
  Minus,
  PieChart,
  Refresh,
  Shop,
  StarFilled,
  Top,
  Trophy,
  Van,
  WarningFilled,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { supplyChainApi } from "@/api/dashboard/supply-chain.api";

// 类型定义
interface SupplyChainDashboardData {
  overviewMetrics: OverviewMetrics;
  inventoryAnalysis: InventoryAnalysis;
  turnoverAnalysis: TurnoverAnalysis;
  targetAchievement: TargetAchievement;
  storePerformanceList: StorePerformance[];
  inventoryAlerts: InventoryAlert[];
  trendData?: TrendData;
}

interface OverviewMetrics {
  totalInventoryAmount: number;
  totalInventoryQuantity: number;
  spotAmount: number;
  inTransitAmount: number;
  avgTurnoverDays: number;
  alertProductCount: number;
  activeStoreCount: number;
  pvSpotRate: number;
}

interface InventoryAnalysis {
  spotRatio: number;
  inTransitRatio: number;
  inventoryHealthStatus: string;
  distributionData: InventoryDistribution[];
}

interface InventoryDistribution {
  category: string;
  amount: number;
  percentage: number;
}

interface TurnoverAnalysis {
  fastTurnoverCount: number;
  mediumTurnoverCount: number;
  slowTurnoverCount: number;
  turnoverEfficiencyChange: number;
  bestTurnoverStore: string;
  bestTurnoverDays: number;
}

interface TargetAchievement {
  monthlyNrTarget: number;
  orderedAmount: number;
  achievementRate: number;
  estimatedCompletionDate: string;
  targetStatus: string;
  targetGap: number;
}

interface StorePerformance {
  id?: number;
  storeName: string;
  inventoryAmount: number;
  turnoverDays: number;
  achievementRate: number;
  pvSpotRate: number;
  ranking: number;
  trend: "up" | "down" | "stable";
}

interface InventoryAlert {
  storeName: string;
  alertType: "low_stock" | "overstock" | "slow_turnover";
  alertLevel: "high" | "medium" | "low";
  alertDescription: string;
  estimatedStockoutDays?: number;
  recommendedAction: string;
}

interface TrendData {
  inventoryAmountTrend: TrendPoint[];
  turnoverDaysTrend: TrendPoint[];
  achievementRateTrend: TrendPoint[];
}

interface TrendPoint {
  date: string;
  value: number;
  label: string;
}

// 响应式数据
const loading = ref(false);
const updateTime = ref("");
const dateRange = ref<[string, string]>(["", ""]);
const sortBy = ref("achievementRate");
const selectedTrend = ref("inventory");

// 看板数据
const overviewData = reactive<OverviewMetrics>({
  totalInventoryAmount: 0,
  totalInventoryQuantity: 0,
  spotAmount: 0,
  inTransitAmount: 0,
  avgTurnoverDays: 0,
  alertProductCount: 0,
  activeStoreCount: 0,
  pvSpotRate: 0,
});

const inventoryData = reactive<InventoryAnalysis>({
  spotRatio: 0,
  inTransitRatio: 0,
  inventoryHealthStatus: "良好",
  distributionData: [],
});

const turnoverData = reactive<TurnoverAnalysis>({
  fastTurnoverCount: 0,
  mediumTurnoverCount: 0,
  slowTurnoverCount: 0,
  turnoverEfficiencyChange: 0,
  bestTurnoverStore: "",
  bestTurnoverDays: 0,
});

const targetData = reactive<TargetAchievement>({
  monthlyNrTarget: 0,
  orderedAmount: 0,
  achievementRate: 0,
  estimatedCompletionDate: "",
  targetStatus: "正常",
  targetGap: 0,
});

const storeRanking = ref<StorePerformance[]>([]);
const alertList = ref<InventoryAlert[]>([]);

// 图表实例
const inventoryChartRef = ref<HTMLElement>();
const trendChartRef = ref<HTMLElement>();
let inventoryChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 格式化函数
function formatCurrency(value: number): string {
  if (!value) return "0";
  return value.toLocaleString("zh-CN", {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  });
}

function formatPercentage(value: number): string {
  if (!value) return "0%";
  return `${value.toFixed(1)}%`;
}

// 状态类型获取函数
function getHealthStatusType(status: string): string {
  const statusMap: Record<string, string> = {
    优秀: "success",
    良好: "primary",
    一般: "warning",
    较差: "danger",
  };
  return statusMap[status] || "info";
}

function getTargetStatusType(status: string): string {
  const statusMap: Record<string, string> = {
    正常: "success",
    预警: "warning",
    紧急: "danger",
  };
  return statusMap[status] || "info";
}

function getAlertLevelType(level: string): string {
  const levelMap: Record<string, string> = {
    high: "danger",
    medium: "warning",
    low: "info",
  };
  return levelMap[level] || "info";
}

function getAlertLevelText(level: string): string {
  const levelMap: Record<string, string> = {
    high: "高",
    medium: "中",
    low: "低",
  };
  return levelMap[level] || "未知";
}

function getProgressColor(percentage: number): string {
  if (percentage >= 90) return "#67c23a";
  if (percentage >= 70) return "#409eff";
  if (percentage >= 50) return "#e6a23c";
  return "#f56c6c";
}

// 事件处理函数
function handleDateChange(dates: [string, string] | null) {
  if (dates) {
    loadDashboardData();
  }
}

function handleSortChange() {
  loadStorePerformance();
}

function handleTrendChange() {
  updateTrendChart();
}

async function refreshData() {
  await loadDashboardData();
  ElMessage.success("数据刷新成功");
}

// 数据加载函数
async function loadDashboardData() {
  try {
    loading.value = true;
    const [startDate, endDate] = dateRange.value;

    const data = await supplyChainApi.getDashboardData({
      startDate,
      endDate,
    });

    // 更新各模块数据
    Object.assign(overviewData, data.overviewMetrics);
    Object.assign(inventoryData, data.inventoryAnalysis);
    Object.assign(turnoverData, data.turnoverAnalysis);
    Object.assign(targetData, data.targetAchievement);

    storeRanking.value = data.storePerformanceList || [];
    alertList.value = data.inventoryAlerts || [];

    updateTime.value = new Date().toLocaleString();

    // 更新图表
    await nextTick();
    updateInventoryChart();
    updateTrendChart();
  } catch (error) {
    console.error("加载看板数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
}

async function loadStorePerformance() {
  try {
    const response = await supplyChainApi.getStorePerformance({
      sortBy: sortBy.value,
      limit: 10,
    });
    storeRanking.value = response;
  } catch (error) {
    console.error("加载店铺排行失败:", error);
  }
}

// 图表更新函数
function updateInventoryChart() {
  if (!inventoryChart || !inventoryData.distributionData?.length) return;

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c}万元 ({d}%)",
    },
    legend: {
      bottom: "5%",
      left: "center",
    },
    series: [
      {
        name: "库存分布",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "45%"],
        data: inventoryData.distributionData.map((item: InventoryDistribution) => ({
          value: item.amount,
          name: item.category,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        itemStyle: {
          borderRadius: 4,
        },
      },
    ],
    color: ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C"],
  };

  inventoryChart.setOption(option);
}

function updateTrendChart() {
  if (!trendChart) return;

  // 模拟趋势数据
  const dates = [];
  const values = [];
  const today = new Date();

  for (let i = 29; i >= 0; i--) {
    const date = new Date(today);
    date.setDate(date.getDate() - i);
    dates.push(date.toLocaleDateString());

    // 根据选择的趋势类型生成不同的模拟数据
    let value: number;
    switch (selectedTrend.value) {
      case "inventory":
        value = 2500 + Math.random() * 500;
        break;
      case "turnover":
        value = 35 + Math.random() * 15;
        break;
      case "achievement":
        value = 60 + Math.random() * 25;
        break;
      default:
        value = 0;
    }
    values.push(Math.round(value * 10) / 10);
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
      },
    },
    xAxis: {
      type: "category",
      data: dates,
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
      name:
        selectedTrend.value === "inventory"
          ? "万元"
          : selectedTrend.value === "turnover"
            ? "天"
            : "%",
    },
    series: [
      {
        data: values,
        type: "line",
        smooth: true,
        symbol: "circle",
        symbolSize: 6,
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          opacity: 0.3,
        },
        itemStyle: {
          color: "#409EFF",
        },
      },
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true,
    },
  };

  trendChart.setOption(option);
}

// 图表初始化
function initCharts() {
  if (inventoryChartRef.value) {
    inventoryChart = echarts.init(inventoryChartRef.value);
  }

  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value);
  }

  // 响应式处理
  window.addEventListener("resize", () => {
    inventoryChart?.resize();
    trendChart?.resize();
  });
}

// 生命周期
onMounted(async () => {
  // 设置默认日期范围
  const today = new Date();
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(today.getDate() - 30);

  dateRange.value = [thirtyDaysAgo.toISOString().split("T")[0], today.toISOString().split("T")[0]];

  // 初始化图表
  await nextTick();
  initCharts();

  // 加载数据
  await loadDashboardData();
});
</script>

<style scoped lang="scss">
.supply-chain-dashboard {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .header-left {
      .dashboard-title {
        display: flex;
        align-items: center;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 8px 0;

        .title-icon {
          margin-right: 12px;
          color: #409eff;
        }
      }

      .update-time {
        color: #909399;
        font-size: 14px;
      }
    }

    .header-controls {
      display: flex;
      gap: 16px;
      align-items: center;
    }
  }

  .overview-metrics {
    margin-bottom: 24px;

    .metrics-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 16px;
    }

    .metric-card {
      background: white;
      padding: 24px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      transition:
        transform 0.2s,
        box-shadow 0.2s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }

      .metric-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        font-size: 24px;
        color: white;
      }

      .metric-content {
        flex: 1;

        .metric-value {
          font-size: 28px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
          margin-bottom: 8px;
        }

        .metric-label {
          color: #606266;
          font-size: 14px;
        }
      }

      &.total-inventory .metric-icon {
        background: linear-gradient(135deg, #409eff, #66b3ff);
      }

      &.spot-amount .metric-icon {
        background: linear-gradient(135deg, #67c23a, #85ce61);
      }

      &.transit-amount .metric-icon {
        background: linear-gradient(135deg, #e6a23c, #f0c78a);
      }

      &.turnover-days .metric-icon {
        background: linear-gradient(135deg, #909399, #b1b3b8);
      }

      &.alert-count .metric-icon {
        background: linear-gradient(135deg, #f56c6c, #f89898);
      }

      &.active-stores .metric-icon {
        background: linear-gradient(135deg, #9966cc, #b399d9);
      }

      &.pv-spot-rate .metric-icon {
        background: linear-gradient(135deg, #ff6b9d, #ff8fb3);
      }

      &.achievement-rate .metric-icon {
        background: linear-gradient(135deg, #ffa726, #ffcc80);
      }
    }
  }

  .main-analysis,
  .target-and-ranking,
  .alerts-and-trends {
    margin-bottom: 24px;
  }

  .analysis-card {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    height: 100%;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .efficiency-change {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 14px;
        font-weight: 500;

        .trend-up {
          color: #67c23a;
        }

        .trend-down {
          color: #f56c6c;
        }
      }

      .sort-selector {
        width: 120px;
      }

      .alert-badge {
        .el-icon {
          color: #f56c6c;
        }
      }
    }

    .card-content {
      padding: 24px;
    }
  }

  .inventory-chart-container {
    height: 300px;
    margin-bottom: 16px;

    .chart-container {
      width: 100%;
      height: 100%;
    }
  }

  .inventory-stats {
    display: flex;
    justify-content: space-around;

    .stat-item {
      text-align: center;

      .stat-label {
        display: block;
        color: #909399;
        font-size: 14px;
        margin-bottom: 4px;
      }

      .stat-value {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .turnover-distribution {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;

    .turnover-item {
      text-align: center;
      padding: 16px;
      border-radius: 6px;

      &.fast {
        background: #f0f9ff;
        color: #1890ff;
      }

      &.medium {
        background: #f9f9f0;
        color: #fa8c16;
      }

      &.slow {
        background: #fff2f0;
        color: #ff4d4f;
      }

      .turnover-label {
        font-size: 12px;
        margin-bottom: 8px;
      }

      .turnover-count {
        font-size: 24px;
        font-weight: 600;
      }
    }
  }

  .best-performance {
    .best-store {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px;
      background: #f8f9fa;
      border-radius: 6px;
      font-size: 14px;
      color: #606266;

      .star-icon {
        color: #ffa726;
      }
    }
  }

  .target-progress {
    .progress-info {
      margin-bottom: 20px;

      .progress-labels {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 14px;
        color: #606266;
      }
    }

    .target-details {
      .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 14px;

        .label {
          color: #909399;
        }

        .value {
          font-weight: 500;
          color: #303133;

          &.gap {
            color: #f56c6c;
          }
        }
      }
    }
  }

  .ranking-table {
    .table-header,
    .table-row {
      display: grid;
      grid-template-columns: 60px 1fr 100px 80px 80px 80px 60px;
      gap: 16px;
      align-items: center;
      padding: 12px 0;
      font-size: 14px;
    }

    .table-header {
      font-weight: 600;
      color: #909399;
      border-bottom: 1px solid #f0f0f0;
    }

    .table-row {
      border-bottom: 1px solid #f8f9fa;
      color: #606266;

      &.top-performer {
        background: #f0f9ff;
      }

      &:hover {
        background: #f5f7fa;
      }

      .rank-number {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        color: white;

        &.rank-1 {
          background: #ffa726;
        }

        &.rank-2 {
          background: #bdbdbd;
        }

        &.rank-3 {
          background: #d4af37;
        }
      }

      .trend-up {
        color: #67c23a;
      }

      .trend-down {
        color: #f56c6c;
      }

      .trend-stable {
        color: #909399;
      }
    }
  }

  .alert-list {
    max-height: 400px;
    overflow-y: auto;

    .alert-item {
      padding: 16px;
      border-radius: 6px;
      margin-bottom: 12px;
      border-left: 4px solid transparent;

      &.alert-high {
        background: #fef0f0;
        border-left-color: #f56c6c;
      }

      &.alert-medium {
        background: #fdf6ec;
        border-left-color: #e6a23c;
      }

      &.alert-low {
        background: #f0f9ff;
        border-left-color: #409eff;
      }

      .alert-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .alert-store {
          font-weight: 600;
          color: #303133;
        }
      }

      .alert-description {
        color: #606266;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .alert-action {
        display: flex;
        align-items: center;
        gap: 6px;
        color: #409eff;
        font-size: 13px;

        .el-icon {
          color: #ffa726;
        }
      }
    }
  }

  .chart-container {
    width: 100%;
    height: 300px;
  }

  // 响应式设计
  @media (max-width: 1200px) {
    .overview-metrics .metrics-grid {
      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    }

    .ranking-table {
      .table-header,
      .table-row {
        grid-template-columns: 50px 1fr 90px 70px 70px 70px 50px;
        gap: 12px;
        font-size: 13px;
      }
    }
  }

  @media (max-width: 768px) {
    padding: 16px;

    .dashboard-header {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .header-controls {
        justify-content: center;
      }
    }

    .overview-metrics .metrics-grid {
      grid-template-columns: 1fr;
    }

    .target-and-ranking,
    .alerts-and-trends {
      .el-col {
        margin-bottom: 16px;
      }
    }

    .ranking-table {
      .table-header,
      .table-row {
        grid-template-columns: 40px 1fr 80px 60px;
        gap: 8px;

        .rate-col,
        .spot-col,
        .trend-col {
          display: none;
        }
      }
    }
  }
}
</style>
